package resource

import (
	"bytes"
	"log"
	"os"
	"os/exec"
)

type FileInfo struct {
	Path    string
	Content *bytes.Buffer
}

func (f *FileInfo) Write(p []byte) (n int, err error) {
	return f.Content.Write(p)
}

func (f *FileInfo) Create() error {
	fo, err := os.Create(f.Path)
	if err != nil {
		return err
	}
	fo.Write(f.Content.Bytes())
	fo.Close()
	return nil
}

func CreateFile() VisitorFunc {
	return func(info *Info, err error) error {
		for _, v := range info.Files {
			err = v.Create()
			if err != nil {
				return err
			}
			goFmt(v.Path)(info, nil)
		}
		return nil
	}
}

func goFmt(path string) VisitorFunc {
	return func(info *Info, err error) error {
		cmd := exec.Command("gofmt", "-w", "-s", path)
		err = cmd.Run()
		if err != nil {
			log.Fatalf("cmd.Run() failed with %s\n", err)
		}
		return nil
	}
}
